package com.codedancer.campus.manager.async;

import cn.hutool.json.JSONUtil;
import com.codedancer.campus.common.constant.DataCacheKey;
import com.codedancer.campus.common.utils.RedisUtil;
import com.codedancer.campus.mapper.RoleMapper;
import com.codedancer.campus.po.Role;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 角色异步任务
 */
@Component
@Slf4j
public class RoleAsync {

    @Autowired
    private RoleMapper roleMapper;

    @Resource(name = "dataCacheRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 更新角色编码缓存
     */
    public void updateRoleEncodeDataCache() {
        log.info("开始执行更新角色编码缓存异步任务");
        redisUtil.setRedisTemplate(stringRedisTemplate);
        redisUtil.delete(DataCacheKey.ROLE_ENCODE_DATA_KEY);
        // 查询全部角色
        List<Role> roles = roleMapper.selectList(null);
        List<String> roleEncodes = roles.stream().map(Role::getEncode).collect(Collectors.toList());
        redisUtil.setStringValue(DataCacheKey.ROLE_ENCODE_DATA_KEY,
            JSONUtil.toJsonStr(roleEncodes));
        log.info("更新角色编码缓存异步任务完成");
    }
}
